package com.zhang.runner;

import cn.hutool.crypto.asymmetric.RSA;
import com.zhang.constants.CacheConstant;
import com.zhang.service.RedisService;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Component;


/**
 * 负责将生成的RSA密钥对保存在内存中
 */
@Component
public class RsaRunner implements ApplicationRunner {

    RedisService redisService;


    private AsyncTaskExecutor taskExecutor;

    public RsaRunner(RedisService redisService, AsyncTaskExecutor taskExecutor) {
        this.redisService = redisService;
        this.taskExecutor = taskExecutor;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        taskExecutor.execute(this::generateRsaPair);
    }

    /**
     * TODO rsa无感知更新
     */
    private void generateRsaPair() {

        RSA rsa = new RSA();

        String privateKeyBase64 = rsa.getPrivateKeyBase64();
        String publicKeyBase64 = rsa.getPublicKeyBase64();

        String privateKeyID="";
        String pubKeyID="";

        if (!redisService.hasKey(CacheConstant.RSA_PRIVATE_PREFIX+privateKeyID)){
            redisService.setCacheObject(CacheConstant.RSA_PRIVATE_PREFIX+privateKeyID,privateKeyBase64);
            redisService.setCacheObject(CacheConstant.RSA_PUB_PREFIX+pubKeyID,publicKeyBase64);
        }
    }
}
